import { Contract, ethers } from 'ethers'
import { testNetWork } from './env'
export async function callData () {
  const main = async () => {
    // 1. 创建 provider
    const provider = new ethers.providers.JsonRpcProvider(testNetWork)
    // 2. 创建 wallet 对象
    const privateKey = '5e34716a60a0926d67c629fae8752cdc9fbe742095a093d40e5b1a2834cc981e'
    const wallet = new ethers.Wallet(privateKey,provider)
    // 3. 创建合约实例
    // WETH的ABI
    const abiWETH = [
      "function balanceOf(address) public view returns(uint)",
      "function deposit() public payable",
    ];
    // WETH合约地址（Goerli测试网）
    const addressWETH = '0xb4fbf271143f4fbf7b91a5ded31805e42b2208d6'
    const wethContract = new ethers.Contract(addressWETH,abiWETH,wallet)
    // 4. 调用balanceOf()函数，读取钱包地址address的WETH余额
    // 获取钱包地址
    const address = await wallet.getAddress()
    // 读取WETH合约上的信息
    console.log("\n1. 读取WETH余额")
    // 4.1 编码calldata
    const param1 = wethContract.interface.encodeFunctionData(
      "balanceOf",
      [address]
    )
    console.log('编码的结果',param1)
    // 创建交易
    const tx1 = {
      to: addressWETH,
      data: param1
    }
    // 发起交易
    const balanceOfWETH = await provider.call(tx1)
    console.log(`存款前的WETH持仓${ethers.utils.formatEther(balanceOfWETH)}`)
    // 5. 调用 deposit 函数将 0.001 的 ETH 转成 WETH 
    const param2 = wethContract.interface.encodeFunctionData('deposit')
    console.log(`编码结果${param2}`)
    // 创建交易
    const tx2 = {
      to: addressWETH,
      data: param2,
      value: ethers.utils.parseEther("0.001")
    }
    // 发起交易 写入操作需要 wallet.sendTransaction
    const receipt1 = await wallet.sendTransaction(tx2)
    // 等待交易上链
    await receipt1.wait()
    console.log(`交易详情`)
    console.log(receipt1)
    const balanceWETH_deposit = await wethContract.balanceOf(address)
    console.log(`转换后的持仓${ethers.utils.formatEther(balanceWETH_deposit)}`)
  }
  main()
}